package com.imoblife.brainwavestus.customview;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.util.BitMapFlyweightFactory;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;


public class AbsProductList extends LinearLayout {

	private static final String TAG = "AbsProductList";

	private int mRowNum;

	private OnItemListener mItemClickListener;

	public interface OnItemListener {
		public void onItemClick(View view, String productId);

		public void onItemLoading(View parent, String productId);

	}

	public AbsProductList(Context context) {
		super(context);

	}

	public AbsProductList(Context context, AttributeSet attrs) {
		super(context, attrs);
		load(context, attrs, 0);

	}

	public AbsProductList(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		load(context, attrs, 0);
	}

	private void load(Context context, AttributeSet attrs, int defStyle) {

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.ProductList, defStyle, 0);
		mRowNum = a.getInteger(R.styleable.ProductList_rowNum, 4);
		
		a.recycle();

	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		updateContextView();
	}

	boolean isUpdate = true;

	protected void updateContextView() {
		if (!isUpdate) {
			return;
		}

		System.gc();

		if (mListData == null) {
			mListData = new ArrayList<String>();
		}

		if (isXLargerScreen()) {
			View v = (View) getParent();
			if (v.getWidth() > 0 && v.getHeight() > 0) {
				isUpdate = false;
				updateXLargerView();
			}
		} else {
			isUpdate = false;
			updateNomalView();
		}

	}

	protected void updateNomalView() {
		long prev = System.currentTimeMillis();

		final LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final Iterator iterator = mListData.iterator();

		if (iterator.hasNext()) {

			addItem(inflater, (String) iterator.next());

			postDelayed(new Runnable() {

				public void run() {

					if (mListData != null && iterator.hasNext()) {
						addItem(inflater, (String) iterator.next());
						postDelayed(this, 0);
					}
				}
			}, 0);
		}

	}

	protected void addItem(LayoutInflater inflater, final String id) {

		View prouctView = inflater.inflate(mProductLayout, null);
		prouctView.setOnClickListener(new OnClickListener() {
			String prouctId = id;

			public void onClick(View v) {
				if (mItemClickListener != null) {
					mItemClickListener.onItemClick(v, prouctId);
				}
			}
		});

		initializeProuctView(prouctView, id);

		addView(prouctView, new LayoutParams(LayoutParams.FILL_PARENT,
				(int) (0.5 + 80 * getResources().getDisplayMetrics().density)));
		// break;

	}

	protected void updateXLargerView() {

		View v = (View) getParent();
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout row = null;

		int i = 0;
		for (final String id : mListData) {

			if (i % 4 == 0) {
				row = (LinearLayout) inflater.inflate(R.layout.product_row,
						null);
				addView(row,
						new LayoutParams(LayoutParams.FILL_PARENT, v
								.getHeight() / mRowNum));
			}

			View prouctView = inflater.inflate(mProductLayout, null);

			prouctView.setOnClickListener(new OnClickListener() {
				String prouctId = id;

				public void onClick(View v) {

					if (mItemClickListener != null) {
						mItemClickListener.onItemClick(v, prouctId);
					}

				}
			});

			row.addView(
					prouctView,
					new LayoutParams((v.getWidth() - getPadRight()) / 4, v
							.getHeight() / mRowNum));
			initializeProuctView(prouctView, id);
			i++;
		}

		int offset = (mListData.size() / mRowNum) - mRowNum;

		if (offset < 0) {

			offset *= -1;

			if ((mListData.size() % mRowNum) > 0) {
				offset -= 1;
			}

			for (int j = 0; j < offset; j++) {

				row = (LinearLayout) inflater.inflate(R.layout.product_row,
						null);

				addView(row,
						new LayoutParams(LayoutParams.FILL_PARENT, v
								.getHeight() / mRowNum));
			}

		}

	}

	List<String> bufferList = new ArrayList<String>();

	protected void initializeProuctView(View prouctView, String id) {

		synchronized (bufferList) {
			if (mItemClickListener != null) {
				bufferList.add(id);
				mItemClickListener.onItemLoading(prouctView, id);
			}
		}
	}

	List<String> mListData;

	public void setDataList(List<String> list) {

		System.gc();

		isUpdate = true;

		mListData = list;

		if (getHeight() > 0 && getWidth() > 0) {
			updateContextView();
		}

	}

	public void setOnItemClicker(OnItemListener clickListener) {
		mItemClickListener = clickListener;
	}

	int mProductLayout;

	public void setProductLayout(int resId) {
		mProductLayout = resId;
	}

	public boolean isXLargerScreen() {

		// if (VERSION.SDK_INT < 11) {
		// return false;
		// }

		DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

		float maxW = displayMetrics.widthPixels < displayMetrics.heightPixels ? displayMetrics.widthPixels
				: displayMetrics.heightPixels;

		maxW /= displayMetrics.density;
		maxW += 0.5;
		return maxW >= 552;
	}

	private int getPadRight() {
		return (int) (30 * getResources().getDisplayMetrics().density);
	}

	public void release() {

		synchronized (bufferList) {
			removeAllViews();
			for (String element : bufferList) {
				BitMapFlyweightFactory.getBitMapFlyweightFactory(
						getResources().getAssets()).requestRelease(element);
			}
			bufferList = new ArrayList<String>();
			mListData = null;
		}

		System.gc();
	}

}
